import { Config, Provide } from '@midwayjs/decorator';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { BroadcastFileEntity } from '../entity/file';
const fs = require("fs")
const download = require('download');
const fluent_ffmpeg = require('fluent-ffmpeg')
/**
 * 象数音频文件
 */
@Provide()
export class BroadcastFileService extends BaseService {

  @InjectEntityModel(BroadcastFileEntity)
  broadcastFileEntity: Repository<BroadcastFileEntity>;


  @Config('module.broadcast')
  broConfig;

  /**
  * 新增
  * @param ids
  */
  async add(param) {
    let info = await this.broadcastFileEntity.findOneBy({ name: param.name, type: param.type })
    if (info) {
      throw new CoolCommException(`已存在该类型的同名音频文件,请删除后重新操作`);
    }
    let save_path = `${this.broConfig.savePath}/modules/broadcast/files/${param.type}/${param.name}.mp3`
    // 如果有音频文件,就先删除，再保存
    if (fs.existsSync(save_path)) {
      fs.unlink(save_path, (err) => { })
    }
    // 下载文件到本地
    const data = await download(param.url)
    fs.writeFileSync(save_path, data)
    param.duration = await this.getDuration(save_path)
    return await this.broadcastFileEntity.insert(param)
  }
  /**
   * 获取音频时长
   * @param filePath 
   * @returns 
   */
  async getDuration(filePath) {
    return new Promise<number>((resolve, reject) => {
      fluent_ffmpeg.ffprobe(filePath, (err, metadata) => {
        if (err) reject(err);
        else resolve(Math.round(metadata.format.duration * 100) / 100);
      });
    });
  }
  /**
   * 删除
   * @param ids
   */
  async delete(ids) {
    let idArr;
    if (ids instanceof Array) {
      idArr = ids;
    } else {
      idArr = ids.split(',');
    }
    for (const id of idArr) {
      // 取消删除文件,因为下次新增同名的文件的话会覆盖，防止删除后播放不了的问题
      // let info = await this.broadcastFileEntity.findOneBy({ id })
      // // 删除文件夹下的文件
      // let file = `${this.broConfig.savePath}/modules/broadcast/files/${info.type}/${info.name}.mp3`
      // if (fs.existsSync(file)) {
      //   fs.unlink(file, (err) => { })
      // }
      await this.broadcastFileEntity.delete({ id });
    }
  }
  /**
   * 同步文件
   * 
   */
  async synchronize(param) {
    let file = `${this.broConfig.savePath}/modules/broadcast/files/${param.type}/${param.name}.mp3`
    if (fs.existsSync(file)) {
      throw new CoolCommException(`当前文件已存在`);
    }
    // 下载文件到本地
    const data = await download(param.url)
    fs.writeFileSync(file, data)
    return true
  }
  /**
   * 分页查询
   * @param ids
   */
  async page(query) {

    const { type } = query;

    let result = await this.sqlRenderPage(
      `
      SELECT
          a.*
      FROM
      broadcast_file a
      where 1=1
      ${this.setSql(type, 'and a.type = ?', [type])}
      `,
      query
    );
    result.list.forEach(e => {
      let file = `${this.broConfig.savePath}/modules/broadcast/files/${e.type}/${e.name}.mp3`
      let server_url = ""
      if (fs.existsSync(file)) {
        server_url =`/file/${e.type}/${e.name}.mp3`
      }
      e['server_url'] = server_url;
    });
    return result
  }
}
